<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SetOnOrder
 *
 * @author Administrator
 */
class SetOnOrder extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->service('/wms/inventory_service');
        $this->load->model('/wms/inventory_on_order_model');
    }

    function set_onorder($lstProduct)
    {
        $ref_num = 'wx' . rand(1000000, 9999999);
        $lstProduct = array(
            array(
                'orderId' => $ref_num,
                'sku' => '02010012-0069',
                'whsCode' => 'S001-W1',
                'quantity' => '1'),
            array(
                'orderId' => $ref_num,
                'sku' => '05010000-0074',
                'whsCode' => 'S001-W1',
                'quantity' => '1')
        );
        $checkWhere = array(
            'order_id' => $lstProduct[0]['orderId']
        );
        $check = $this->inventory_on_order_model->get_on_track($checkWhere);
        if ($check)
        {
            echo '已锁定';
            return '订单已锁定库存';
        }
        $skuArray = array();
        $time = time();
        foreach ($lstProduct as $productInfo)
        {
            //检查每个产品的可用库存，一个库存不够不能锁定
            $checkAvailabel = $this->inventory_service->get_available($productInfo['sku'], $productInfo['whsCode']);
            if ($checkAvailabel < $productInfo['quantity'])
            {
                echo '库存不够';
                return $productInfo['sku'] . '产品库存不足';
            }

            $one['order_id'] = $productInfo['orderId'];
            $one['sku'] = $productInfo['sku'];
            $one['whs_code'] = $productInfo['whsCode'];
            $one['quantity'] = $productInfo['quantity'];
            $one['in_or_out'] = 'out';
            $one['type'] = '1';
            $one['created_time'] = $time;
            $skuArray[] = $one;
        }
        if (count($skuArray))
        {
            $rs = $this->set_lst_t($skuArray);
            return $rs;
        }
        else
        {
            return '没有产品数据';
        }
    }

    private function set_by_item(array $itemData)
    {
        //插入数据
        $rs = $this->inventory_on_order_model->insert($itemData);
        $this->inventory_service->set_on_order($itemData['sku'], $itemData['whs_code'], intval($itemData['quantity']));
        return $rs;
    }

    function set_lst_t(array $listData)
    {
        $this->db->trans_begin();
        foreach ($listData as $item)
        {
            $this->set_by_item($item);
        }
        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return false;
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }

}

?>
